/*
 * @Author: C.
 * @Date: 2023-04-25 09:34:03
 */
// getFormMaps, getDescMaps
import { getTableMaps } from '/~/utils/help/createFields';
import { useI18n } from '/@/hooks/web/useI18n';
// const { t } = useI18n();
import { createApiModule } from '/~/utils/help/createApiModule';
import { omit } from 'lodash-es';
import { TableLink } from '/~/components/TableLink';
import { h } from 'vue';
import { dataHandle } from '/~/utils/data';
import { projectSettings } from '../../settings/projectSettings';
type GetType<T> = T extends (arg: infer P) => void ? P : string;
type Colums = GetType<typeof getTableMaps>;
//国内税率模式
const { isForeignTaxMode } = projectSettings;
// 是否使用辅助单价
function useAuxiliary(record: Recordable): boolean {
  return Boolean(record.AuxiliaryPrice) && Boolean(record.AuxiliaryQty);
}
const computedTableColums: Colums = [
  'ItemId',
  'ItemName',
  'Description',
  'Unit',
  [
    'Quantity',
    {
      edit: true,
      // editRule: true,
      editComponent: 'InputNumber',
      defaultValue: 0,
      editComponentProps: {
        min: 0,
      },
      editRule: async (text) => {
        if (Number(text) <= 0) {
          return '数量需要大于0';
        }
        return '';
      },
    },
  ],
  // 扣税单价
  [
    'NoTaxPrice',
    {
      edit: true,
      editRule: true,
      editComponent: 'InputNumber',
      defaultValue: 0,
      ifShow: isForeignTaxMode,
    },
  ],
  [
    'Price',
    {
      // helpMessage: '未税单价*(1+税率)',
      customRender: ({ record }) => {
        let count = 0;

        if (Number(record.Quantity) > 0) {
          count = Number(record.Amount) / Number(record.Quantity);
        }
        record.Price = count;
        return dataHandle(count, 'amount');
      },
      edit: !isForeignTaxMode,
      editRule: !isForeignTaxMode,
      editComponent: 'InputNumber',
      defaultValue: 0,
    },
  ],
  [
    'Amount',
    {
      helpMessage: '数量*单价 或者 辅助数量*辅助单价',
      customRender: ({ record }) => {
        let count = 0;
        // 国内税率
        if (isForeignTaxMode) {
          // 使用辅助单价？
          count = useAuxiliary(record)
            ? record.AuxiliaryPrice * record.AuxiliaryQty
            : record.TDA * (Number(record.Tax) + 1);
        } else {
          count = useAuxiliary(record)
            ? record.AuxiliaryPrice * record.AuxiliaryQty
            : Number(record.Quantity) * Number(record.Price || 0);
          useAuxiliary(record) && (record.Price = count / Number(record.Quantity));
        }
        record.Amount = count;
        return dataHandle(count, 'amount');
      },
    },
  ],
  'Tax',
  // 扣税金额
  [
    'TDA',
    {
      // helpMessage: '数量*未税单价',
      helpMessage: `${isForeignTaxMode ? ' 金额*（税率+1)' : '金额/（税率+1）'}`,
      customRender: ({ record }) => {
        let count = 0;
        // 国内税率
        if (isForeignTaxMode) {
          // 使用辅助单价？
          count = useAuxiliary(record)
            ? record.Amount / (Number(record.Tax) + 1)
            : record.Quantity * record.NoTaxPrice;

          useAuxiliary(record) &&
            (record.NoTaxPrice = dataHandle(count / record.Quantity, 'amount'));
        } else {
          count = record.Amount / (Number(record.Tax) + 1);
        }
        record.TDA = count;
        return dataHandle(count, 'amount');
      },
    },
  ],
];
// 详情表格 base
export const detailTableColums: Colums = [
  'ItemId',
  'ItemName',
  'Description',
  'Unit',
  'Quantity',
  'NoTaxPrice',
  'Price',
  'Amount',
  'Tax',
  'TDA',
];
// 获取可计算的明细编辑表格
export function getComputedTableColums(list: Colums = []) {
  return getTableMaps([
    ...computedTableColums,
    ...list,
    [
      'Remarks',
      {
        edit: true,
        editComponent: 'Input',
        editRule: true,
      },
    ],
  ]);
}
// 获取可计算的明细详情表格
export function getDetailTableColums(list: Colums = []) {
  return getTableMaps([...detailTableColums, ...list, 'Remarks']);
}
//  'AuxiliaryQty'
//  'AuxiliaryPrice'
// 获取带有辅助数量和辅助单价的表格列
export function getAuxiliaryColums() {
  return getComputedTableColums([
    [
      'AuxiliaryQty',
      {
        edit: true,
        editRule: true,
        editComponent: 'InputNumber',
      },
    ],
    [
      'AuxiliaryPrice',
      {
        edit: true,
        editRule: true,
        editComponent: 'InputNumber',
      },
    ],
  ]);
}
// 获取带有辅助数量和辅助单价的表格列
export function getAuxiliaryDetailColums() {
  return getDetailTableColums(['AuxiliaryQty', 'AuxiliaryPrice']);
}

// 处理关联单据
const connectionSymbol = '@';
export async function getTransformData({ TransformId, ApiName, BillKey }) {
  const { api_get } = createApiModule(ApiName);
  const res = await api_get({ BillId: TransformId });
  const BillItems = res.BillItems.map((item) => {
    return {
      Tax: 0,
      ...item,
      AssociatedNo: item.Id,
      Id: 0,
    };
  });
  // 摘除敏感信息 混入AssociatedNo
  return omit(
    {
      ...res,
      AssociatedNo: `${BillKey}${connectionSymbol}${TransformId}`,
      BillItems: BillItems,
    },
    ['AuditNodes', 'BillGui', 'BillId', 'Remarks', 'ShowButtonMode', 'State'],
  );
}
// 解析关联单据
export function RelationLink(params: { target: string }) {
  const { target } = params;
  if (!target) return projectSettings.dataPlaceholder;
  const [BillKey, billId] = target.split(connectionSymbol);
  if (!BillKey || !billId) return target;
  if (!billId) return projectSettings.dataPlaceholder;
  const { t } = useI18n();
  // t('routes.menu.Sa_Order')
  const props = {
    style: {
      display: 'flex',
    },
    display: `From  ` + t(`routes.menu.${BillKey}`),
    text: billId,
    name: `${BillKey}_Detail`,
    query: {
      Id: billId,
    },
  };
  return h(TableLink, props);
}
